package com.example.demo.utils;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class Url2Base64 {
    public static String urlToBase64(String url,String username) throws IOException {
        String[] path=url.split("/");
        if(path[3].equals(username)) {
            String houzhui = url.split("\\.")[4];
            String Base64;
            URL newUrl = new URL(url);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) newUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);//通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();//得到图片的二进制数据，以二进制封装得到数据，具有通用性
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;//使用一个输入流从buffer里把数据读取出来
            while ((len = inStream.read(buffer)) != -1) {//用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            byte[] data = outStream.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            Base64 = encoder.encode(data);
            Base64 = "data:image/" + houzhui + ";base64," + Base64;
            return Base64;//返回Base64编码过的字节数组字符串
        }
        return "越权";
    }
}
